<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="40%"
        :before-close="handleClose">
        <el-form v-if="dialogVisible" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px"
            class="demo-ruleForm">
            <el-form-item label="作业类型" prop="workType">
                <el-select v-model="ruleForm.workType" class="w100p" clearable filterable placeholder="请选择作业类型">
                    <el-option v-for="item, index in workTypeList" :key="index" :label="item.name"
                        :value="item.key"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次(已封塘)" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-row v-if="ruleForm.workType == 'FEEDING'" :gutter="10"
                v-for="item, index in ruleForm.workTaskDetailList" :key="index">
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入物料名称' : ''" :prop="`workTaskDetailList[${index}][materialNo]`"
                        :rules="rules.materialNo">
                        <el-select clearable filterable class=" w100p" v-model="item.materialNo" placeholder="请选择药品">
                            <el-option v-for="item, index in materialList" :key="index" :label="item.materialName"
                                :value="item.materialNo"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入数量' : ''" :prop="`workTaskDetailList[${index}][num]`"
                        :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入参数">
                            <template slot="append">{{ getUnitName(item.materialNo) }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <el-form-item label="作业人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择作业" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo + ''"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="作业时间" prop="taskTemplateTime">
                <el-date-picker v-model="ruleForm.taskTemplateTime" type="datetimerange" @change="handleChangeTime"
                    value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" align="right">
                </el-date-picker>
                <div class="errText">作业开始时间至少是当前时间的30分钟后开始</div>
            </el-form-item>
            <!-- <el-form-item v-show="ruleForm.taskTemplateTime && ruleForm.taskTemplateTime.length == 2" label="提前通知时间"
                prop="workNoticeTime">
                <el-date-picker v-model="ruleForm.workNoticeTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                    :picker-options="pickerOptionsDatetime" placeholder="选择日期时间" default-time="12:00:00"
                    @change="handleChangeTime">
                </el-date-picker>
            </el-form-item> -->
            <el-form-item label="任务启用停用">
                <el-switch v-model="ruleForm.status" active-color="#13ce66" inactive-color="#ff4949"
                    :active-value="'ENABLE'" :inactive-value="'DISABLE'" active-text="启用" inactive-text="停用">
                </el-switch>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import jobTaskManagement from '@/api/jobManagment/jobTaskManagement';
import { formatTime } from '@/utils/fmtTime.js';
export default {
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        planList: {
            type: Array,
            default: () => {
                return []
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (Number(value) > 0) { callback() } else {
                callback(new Error('请输入大于0的数值！'))
            }
        };
        return {
            workTypeList: [
                {
                    name: "换水作业",
                    key: 'CHANGE_WATER'
                },
                {
                    name: "漏网作业",
                    key: 'EXPOSED_NET'
                },
                {
                    name: "消杀作业",
                    key: "DISINFECTION_WATER"
                },
                {
                    name: "饲喂作业",
                    key: 'FEEDING'
                },
                {
                    name: "吊网作业",
                    key: 'HANGING_NET'
                }
            ],
            pickerOptionsDatetime: {
                disabledDate(time) {
                    return time.getTime() < Date.now();
                }
            },
            pickerOptions: {
                disabledDate(time) {
                    // 获取当前时间并加上半小时  
                    const currentTime = new Date();
                    currentTime.setTime(currentTime.getTime() + 30 * 60 * 1000);
                    // 如果选择的时间早于当前时间加上半小时，则禁用它  
                    return time.getTime() < currentTime.getTime() - 8.64e7;
                },
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        end.setTime(end.getTime() + 30 * 60 * 1000); // 加上半小时以符合限制  
                        const start = new Date();
                        start.setTime(end.getTime() - 3600 * 1000 * 24 * 7); // 从结束时间减去一周  
                        picker.$emit('pick', [end, start]); // 注意：开始时间应该在前面  
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        end.setTime(end.getTime() + 30 * 60 * 1000); // 加上半小时以符合限制  
                        const start = new Date();
                        start.setTime(end.getTime() - 3600 * 1000 * 24 * 30); // 从结束时间减去一个月  
                        picker.$emit('pick', [end, start]); // 注意：开始时间应该在前面  
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        end.setTime(end.getTime() + 30 * 60 * 1000); // 加上半小时以符合限制  
                        const start = new Date();
                        start.setTime(end.getTime() - 3600 * 1000 * 24 * 90); // 从结束时间减去三个月  
                        picker.$emit('pick', [end, start]); // 注意：开始时间应该在前面  
                    }
                }]
            },
            warningText: '',
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                workType: [
                    { required: true, message: '请选择作业类型', trigger: 'change' }
                ],
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                materialNo: [
                    { required: true, message: '请选择物料', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择作业人', trigger: 'change' }
                ],
                taskTemplateTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
            },
        }
    },

    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        getUnitName(no) {
            let rut = this.materialList.find(item => {
                return item.materialNo == no
            })
            return rut ? rut.unitName : ''
        },
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {
                    status: 'ENABLE'
                }
                this.addEditApi = jobTaskManagement.add
                this.addEditName = '添加'
                this.$set(this.ruleForm, 'workTaskDetailList', [{
                    materialName: null, num: null, materialNo: null
                }])
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                    taskTemplateTime: [this.data.workStartTime, this.data.workEndTime]
                }
                this.addEditApi = jobTaskManagement.edit
                this.addEditName = '编辑'
                if (this.ruleForm.workTaskDetailList && this.ruleForm.workTaskDetailList.length == 0) {
                    this.$set(this.ruleForm, 'workTaskDetailList', [{
                        materialName: null, num: null, materialNo: null
                    }])
                }
                // this.handleChangeTime();
            }
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchName', '');
            this.$set(this.ruleForm, 'batchId', '');
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        handleGetMaterialName(no) {
            console.log(no)
            let row = this.materialList.find(item => Number(item.materialNo) == Number(no));
            return row.materialName;
        },
        handleChangeTime() {
            if (this.ruleForm.taskTemplateTime && this.ruleForm.taskTemplateTime.length == 2) {
                let givenTime = new Date(this.ruleForm.taskTemplateTime[0]);
                let currentTime = new Date();
                let diffInMilliseconds = Math.abs(givenTime - currentTime);
                let diffInMinutes = Math.floor(diffInMilliseconds / 1000 / 60);
                if ((givenTime - currentTime) < 0 || diffInMinutes <= 15) {
                    this.ruleForm.taskTemplateTime[0] = this.getTime(currentTime, -30)
                }
            }
        },
        getTime(time, minute = 1) {
            let givenTime = new Date(time);
            givenTime.setTime(givenTime.getTime() - minute * 60000);
            return formatTime(givenTime, 'yyyy-MM-dd HH:mm:ss')
        },
        addMaterial() {
            let length = this.ruleForm.workTaskDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.workTaskDetailList, length, {
                    materialName: null, num: null, materialNo: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.workTaskDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'workTaskDetailList', list)
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.ruleForm.workType !== 'FEEDING') {
                        this.ruleForm.workTaskDetailList = []
                    }
                    if (this.ruleForm.workTaskDetailList && this.ruleForm.workTaskDetailList.length > 0) {
                        this.ruleForm.workTaskDetailList.forEach(item => {
                            item.materialName = this.handleGetMaterialName(item.materialNo)
                        })
                    };
                    let params = {
                        workStartTime: this.ruleForm.taskTemplateTime[0],
                        workEndTime: this.ruleForm.taskTemplateTime[1],
                        taskCreate: 'MANUAL_WORK'
                    };
                    if (this.addEditFlag == 'add') {
                        this.handleChangeTime();
                    }
                    delete this.ruleForm.taskTemplateTime;
                    this.addEditApi({ ...this.ruleForm, ...params }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败';
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg);
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err);
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.warningText = '';
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
        },
        //取消关闭
        cancel() {
            this.resetForm();
            this.$emit("closeDialog");
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); done(); })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item__content {
        margin: 0 !important;
    }

    .el-form-item {
        .label {
            display: none;
        }


    }
}

.elRow {
    text-align: center;
}
</style>